from PyQt5 import QtWidgets, QtGui, QtCore
import soc_gui
import sys, array, threading
import numpy as np
import pyqtgraph as pg
import pyserial1


def abortReceive():
	pyserial1.ser.cancel_read()

def createWatchingThread():
	#Create thread listening on port
	thread_receive = threading.Thread(target=receiveData)
	thread_receive.start()

def comboBox_2Activated(port):
	global serial_port
	serial_port = port

def comboBox_3Activated(baudrate):
	global serial_baudrate
	serial_baudrate = baudrate

def readSerialState():
	available_com_ports = pyserial1.getAvailableComPorts()
	for a in range(len(available_com_ports)):
		ui.comboBox_2.addItem(available_com_ports[a])

def openPort():
	global serial_port, serial_baudrate, portflag
	serial_port = ui.comboBox_2.currentText()
	serial_baudrate = ui.comboBox_3.currentText()
	if not portflag:
		portflag = 1
		pyserial1.setComPort(serial_port, serial_baudrate)
		pyserial1.openSerialPort()
		createWatchingThread()

def closePort():
	global portflag
	if portflag:
		abortReceive()
		portflag = 0
		#Reset serial input buffer to get a clean enviroment at next communication
		pyserial1.ser.reset_input_buffer()
		pyserial1.closeSerialPort()

def initVariables():
	global data_array, portflag
	portflag = 0
	init_list = list()
	for a in range(100):
		init_list.append(0)
	data_array = np.array(init_list)

def updateDisplay():
	global curve, data_array
	curve.setData(data_array)
	

def receiveData():
	global data_array, portflag
	count = 0
	thread_exit_flag = 0
	data_buffer = ''
	while True:
		if not portflag:
			break
		if count == 100:
			count = 0
		while True:
			byte_buffer = pyserial1.ser.read()
			if byte_buffer.decode('ascii') == ' ':	#Set a ' ' as stop symbol for a single number data
				break
			data_buffer += byte_buffer.decode('ascii')
		data_array[count] = float(data_buffer)
		count += 1
		data_buffer = ''



if __name__ == '__main__':
	#Initiate variables
	initVariables()

	#Initiate UI
	app = QtWidgets.QApplication(sys.argv)
	MainWindow = QtWidgets.QMainWindow()
	ui = soc_gui.Ui_MainWindow()
	ui.setupUi(MainWindow)

	#Read serial state
	#readSerialState()
	#timer2 = QtCore.QTimer()
	#timer.timeout.connect(readSerialState)
	#timer.start(2)

	#Initiate timer for updating display
	curve = ui.graphicsView_wave.plot(pen='y')	#Set pen style used to plot
	timer = QtCore.QTimer()
	timer.timeout.connect(updateDisplay)
	timer.start(50)

	#Following: Config MainWindow
	MainWindow.showMaximized()
	MainWindow.tabifyDockWidget(ui.dockWidget_control, ui.dockWidget_measure)
	MainWindow.tabifyDockWidget(ui.dockWidget_measure, ui.dockWidget_control)

	#Configure signal slots
	#ui.pushButton_open_port.clicked.connect(openPort)
	#ui.pushButton_close_port.clicked.connect(closePort)
	#ui.comboBox_2.activated[str].connect(comboBox_2Activated)
	#ui.comboBox_3.activated[str].connect(comboBox_3Activated)
	
	#ui.graphicsView_preview.setVisible(False)

	#Following: Set view size mode when changing window size
	ui.splitter.setStretchFactor(1,1)

	#Set initial splitter position for send and receive text browser
	ui.splitter_4.setSizes([400,150])	

	#Following: UI state initialization
	ui.pushButton_preview_view.setChecked(False)
	ui.comboBox_16.setCurrentIndex(3)
	ui.actionSerialMonitor.trigger()


	MainWindow.show()
	exit_code = app.exec_()
	pyserial1.closeSerialPort()
	sys.exit(exit_code)